#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : userdata.py
# @Author: shadow
# @Date  : 2019/12/4
# @Desc  : read and write userdata msg

# import xlrd, xlwt
from collections import namedtuple
import csv

User = namedtuple('user', 'num, name, passwd, balance, telephone, flag')
users = [User(1, "admin", "admin123", 10000, "13585857885\t", 100), User(2, "shadow", "123456\t", 5000, "13838383388\t", 10)]


# 写入用户信息到数据表
def add_user(user: User):
    try:
        with open("UserInfo.csv", "a", newline="") as f:  # newline="" 设置写完后不会留空行
            writer = csv.writer(f)
            writer.writerow(user)
        return True
    except:
        return False


# def write_user():
#     work = xlwt.Workbook(encoding="utf-8")
#     sheet = work.add_sheet("userInfo")
#     sheet.col(2).width = 256*16
#     sheet.col(3).width = 256*16
#
#     def write_one():
#         sheet.write(0, 0, label="NUM")
#         sheet.write(0, 1, label="NAME")
#         sheet.write(0, 2, label="PASSWORD")
#         sheet.write(0, 3, label="BALANCE")
#         sheet.write(0, 4, label="TELEPHONE")
#         n = 1
#         for user in users:
#             sheet.write(n, 0, label=user.num)
#             sheet.write(n, 1, label=user.name)
#             sheet.write(n, 2, label=user.passwd)
#             sheet.write(n, 3, label=user.balance)
#             sheet.write(n, 4, label=user.telephone)
#             n += 1
#         work.save('userInfo.xls')


# 获取所有用户
def get_users():
    users = []
    # for xlrd
    # data = xlrd.open_workbook('userInfo.xls')
    # table = data.sheet_by_name("userInfo")
    # # for i in table.get_rows():
    # #     print(i)
    #
    # for num in range(1, table.nrows):
    #     user = table.row_values(num)

    # 使用csv.reader会默认去掉空白符
    # with open("UserInfo.csv") as f:
    #     reader = csv.reader(f)
    #     for user in reader:
    #         if user[0].isdigit():
    #             users.append(User(int(user[0]), user[1], user[2], int(user[3]), user[4]))
    with open("UserInfo.csv") as f:
        for line in f.readlines():
            tmp = line.split(",")
            if tmp[0].isdigit():
                users.append(User._make(tmp))
    return users


#  查找用户, 返回用户信息字典
def find_user(user, option=1):
    """
    :param user: user name or num
    :param option: 0: num, 1:name, -1:all
    :return: OrderedDict of the userInfo if find the user,otherwise None
    """
    with open("UserInfo.csv") as f:
        for line in f.readlines():
            tmp = line.split(",")   # 数据全部变成了字符串
            # print(tmp, user, option)
            if tmp[option] == user:
                tmp[0] = int(tmp[0])  # 账号是数字
                tmp[3] = int(tmp[3])  # 余额是数字
                return User._make(tmp)._asdict()  # 列表转命名元组再转字典
        else:
            return False


from itertools import islice
def get_all():
    with open("UserInfo.csv") as f:
        for line in islice(f, 1, None):  # 跳过第一行
        # for line in f.readlines():
            tmp = line.split(",")  # 数据全部变成了字符串
            yield User._make(tmp)  # 返回用户命名元组


# 改变用户余额, csv不能直接修改，最好利用数据库来存储
def change_balance(user):
    """
    :param user: OrderedDict, (num, name, passwd, balance, telephone)
    """

    # print(__name__, "change_balance",  user)
    file_data = ""
    flag = False
    with open("UserInfo.csv") as f:
        for line in f.readlines():
            if line.split(",", 2)[:2] == [str(user["num"]), user["name"]]:  # 账号和用户名相同，确认是该账户
                user["num"] = str(user["num"])
                user["balance"] = str(user["balance"])
                line = ",".join(user.values())
                flag = True
            file_data += line
        else:
            if not flag:
                return False

    with open("UserInfo.csv", "w") as f:
            f.write(file_data)
    return True
    # data = pd.read_csv('UserInfo.csv', encoding='utf-8')
    # print(data)
    # # data[u'buy_place'] = data[u'buy_place'].astype(str)
    # # data[u'buy_place'] = data[u'buy_place'].apply(lambda x: x.split(' ')[-1])
    # # data.to_csv('UserInfo.csv', index=False, encoding='utf-8')

def change_info(user):
    """
    :param user: userinfo string, as: num,name,passwoed,balance,telephone
    :return:
    """
    file_data = ""
    flag_del = False
    user_info = user.split(",")

    with open("UserInfo.csv") as f:
        for line in f.readlines():
            tmp = line.split(",")
            if tmp[0] == user_info[0]:  # 账号相同即修改
                if user_info[-1] == "0":  # 删除用户
                    flag_del = True
                    continue
                else:   # 赋给新的数据
                    line = user

            # if flag_del:    # 账号顺移
            #     line = line.replace(tmp[0], str(int(tmp[0]) -1), 1)
            file_data += line

    with open("UserInfo.csv", "w") as f:
        f.write(file_data)
    return True


# add_user(["NUM", "NAME", "PASSWORD", "BALANCE", "TELEPHONE"])
# add_user(users[0])
# add_user(users[1])
# 写的很棒~